package com.feinno.urcs.group.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Li.Hongbo <lihongbo@feinno.com>
 */
public class FileDownloadHttpClient {
	private static final Logger LOGGER = LoggerFactory.getLogger(FileDownloadHttpClient.class);

	public static byte[] getFile(String fileUrl) throws IOException {
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		ByteArrayOutputStream bos = null;
		try {
			URL url = new URL(fileUrl);
			bos = new ByteArrayOutputStream();
			// 建立链接
			httpUrl = (HttpURLConnection) url.openConnection();
			// 连接指定的资源
			httpUrl.connect();
			// 获取网络输入流
			bis = new BufferedInputStream(httpUrl.getInputStream());
			// 建立文件
			if (LOGGER.isInfoEnabled())
				LOGGER.info(String.format("downloading [ %s ] ", fileUrl));

			int size = 0;
			byte[] buffer = new byte[1024];
			while ((size = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, size);
			}

			return bos.toByteArray();
		} catch (Exception e) {
			LOGGER.error(String.format(" download [ %s ] error", fileUrl), e);

		} finally {
			bis.close();
			httpUrl.disconnect();
		}
		return null;
	}

	public static byte[] getFileWithHeader(String fileUrl) throws IOException {
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		ByteArrayOutputStream bos = null;
		try {
			URL url = new URL(fileUrl);
			bos = new ByteArrayOutputStream();
			// 建立链接
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.setRequestProperty("Accept","*/*");
			// 连接指定的资源
			httpUrl.connect();
			// 获取网络输入流
			bis = new BufferedInputStream(httpUrl.getInputStream());
			// 建立文件
			if (LOGGER.isInfoEnabled())
				LOGGER.info(String.format("downloading [ %s ] ", fileUrl));

			int size = 0;
			byte[] buffer = new byte[1024];
			while ((size = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, size);
			}

			return bos.toByteArray();
		} catch (Exception e) {
			LOGGER.error(String.format(" download [ %s ] error", fileUrl), e);

		} finally {
			bis.close();
			httpUrl.disconnect();
		}
		return null;
	}
}
